/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package UserBeans;

import Action.AccountSessionBeanLocal;
import Action.TicketsSumSessionBeanLocal;
import Entity.Account;
import Entity.Customer;
import Entity.TicketsSummary;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Minh Duong
 */
@ManagedBean
@SessionScoped
public class CartBean {
    @EJB
    private AccountSessionBeanLocal accountSessionBean;

    @EJB
    private TicketsSumSessionBeanLocal ticketsSumSessionBean;
    private List<TicketBean> list;

    public List<TicketBean> getList() {
        return list;
    }

    public void setList(List<TicketBean> list) {
        this.list = list;
    }

    public CartBean(List<TicketBean> list) {
        this.list = list;
    }

    public void addTicket(TicketBean ticket) {
        if (list.contains(ticket)) {
            TicketBean alterticket = list.get(list.indexOf(ticket));
            alterticket.setQuantity(ticket.getQuantity());
        } else {
            list.add(ticket);
        }
    }

    public Boolean removeTicket(TicketBean ticket) {
        if (!list.contains(ticket)) {
            return Boolean.FALSE;
        }
        list.remove(ticket);
        return Boolean.TRUE;
    }

    public int quantity() {
        return list.size();
    }

    public  double totalCost() {
        double total = 0;
        for (TicketBean ticket : list) {
            total += ticket.getTicket().getTicketsCategory().getPrice() * ticket.getQuantity();
        }
        return total;
    }

    public Boolean comitCart() {
        TicketsSummary ts = null;
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
        Customer cu = (Customer) session.getAttribute("customer");
        Account ac = accountSessionBean.getAccountByEmail(cu.getEmail());
        if (ac.getAmount() < totalCost()) {
            return Boolean.FALSE;
        }
        try {
            for (TicketBean ticket : list) {
                ts = new TicketsSummary();
                ts.setTickets(ticket.getTicket());
                ts.setTotalCost(totalCost());
                ts.setTotalQuantity(ticket.getQuantity());
                ts.setCustomer(null);
                ticketsSumSessionBean.addCart(ts);
                return Boolean.TRUE;
            }
        } catch (Exception ex) {
            return Boolean.FALSE;
        }
        return Boolean.FALSE;
    }
}
